package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.domain.Category;
import org.example.domain.R;
import org.example.service.CategoryService;
import org.example.service.impl.CategoryServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("success");
    }

    @GetMapping("/page")
    public R<Page> select(int page, int pageSize) {
        Page<Category> categoryPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort);
        Page<Category> page1 = categoryService.page(categoryPage, categoryLambdaQueryWrapper);
        return R.success(page1);
    }

    @DeleteMapping
    public R<String> remove(Long[] ids) {
        ArrayList<Long> longs = new ArrayList<>();
        for (Long id :
                ids) {
            longs.add(id);
        }

        categoryService.removeByIds(longs);
        return R.success("success");
    }

    @PutMapping
    public R<String> put(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("success");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        queryWrapper.orderByAsc(Category::getSort);
        queryWrapper.orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);

        return R.success(list);
    }


}
